package com.superman.supermarket.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.superman.mvpframe.client.gin.XGinjector;
import com.superman.mvpframe.client.mvp.MyActivityManager;
import com.superman.mvpframe.client.mvp.MyPlaceController;
import com.superman.mvpframe.client.mvp.MyPlaceHistoryHandler;
import com.superman.mvpframe.client.utils.DomUtils;
import com.superman.mvpframe.client.utils.MobileUtils;
import com.superman.supermarket.client.event.ShopBaseEventHandler;
import com.superman.supermarket.client.gin.ShopGinjector;
import com.superman.supermarket.client.mvp.MyHistoryMapper;
import com.superman.supermarket.client.mvp.MyPlaceFactory;
import com.superman.supermarket.client.utils.ActivityJumpUrl;
import com.superman.supermarket.client.utils.LazyLoadUtils;
import com.superman.supermarket.client.utils.LoginUtils;

/**
 * 这是整个项目的主入口类.主要负责初始化整个mvp框架
 * 
 * @author superman
 * @version 2018年7月5日下午9:28:16
 */
public class supermarket implements EntryPoint {

	private final String LAZY_LOAD_WRAPPER_ID = "gwt-wrapperpanel";

	@Override
	public void onModuleLoad() {
		DomUtils.bindFastClick();
		MobileUtils.setPageBgColor("#f1f1f1");

		final EventBus eventBus = XGinjector.INSTANCE.getEventBus();
		final MyPlaceController placeController = XGinjector.INSTANCE.getMyPlaceController();

		MyHistoryMapper historyMapper = ShopGinjector.INSTANCE.getMyHistoryMapper();
		final MyPlaceFactory placeFactory = ShopGinjector.INSTANCE.getMyPlaceFactory();

		historyMapper.setFactory(placeFactory);

		SimplePanel display = new SimplePanel();
		display.getElement().setId(LAZY_LOAD_WRAPPER_ID);

		MyActivityManager activityManager = new MyActivityManager(eventBus);

		activityManager.setDisplay(display);

		RootPanel.get().add(display);

		final MyPlaceHistoryHandler historyHandler = new MyPlaceHistoryHandler(historyMapper, XGinjector.INSTANCE.getHtml5Historian());

		new ShopBaseEventHandler().bind();

		if (ActivityJumpUrl.isNotPayNotifyUrl()) {
			historyHandler.register(placeController, eventBus, placeFactory.getHomePlace());
		} else {
			XGinjector.INSTANCE.getUserModel().readFromCache();
			historyHandler.register(placeController, eventBus, placeFactory.getCasherDeskPlace());
		}

		LazyLoadUtils.lazyload(LAZY_LOAD_WRAPPER_ID);

		LoginUtils.authLogin(new AsyncCallback<Void>() {

			@Override
			public void onFailure(Throwable caught) {
				historyHandler.handleCurrentHistory();
			}

			@Override
			public void onSuccess(Void result) {
				historyHandler.handleCurrentHistory();
			}
		});

	}

}
